import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _omit from "lodash/omit";
import _isNil from "lodash/isNil";
import _isNumber from "lodash/isNumber";
import React from 'react';
import { Form, Row, Col } from 'antd';
import { getRender, getFormItemComponent, preAdapterInitValue, traversalFormItems, adapterStandardFormIndividual, customizeFormRules, coverConfig, adjustRowAndCol, getComputeComp, selfValidator } from "./customizeTool";
var fixedMap = {
  L: 'left',
  R: 'right'
};
export function generateFormSkeleton() {
  var rows = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var options = arguments.length > 2 ? arguments[2] : undefined;
  var _config$fields = config.fields,
      fields = _config$fields === void 0 ? [] : _config$fields,
      _readOnly2 = config.readOnly,
      _config$maxCol = config.maxCol,
      maxCol = _config$maxCol === void 0 ? 3 : _config$maxCol,
      _config$labelCol = config.labelCol,
      unitLabelCol = _config$labelCol === void 0 ? 9 : _config$labelCol,
      _config$wrapperCol = config.wrapperCol,
      unitWrapperCol = _config$wrapperCol === void 0 ? 15 : _config$wrapperCol;
  var allConfigFields = [];
  var newFields = [];
  fields.forEach(function (i) {
    allConfigFields.push(i.fieldCode);
    newFields.push(i);
  });
  var form = options.form,
      _options$dataSource = options.dataSource,
      dataSource = _options$dataSource === void 0 ? {} : _options$dataSource,
      getValueFromCache = options.getValueFromCache,
      code = options.code,
      className = options.className,
      unitData = options.unitData,
      _readOnly1 = options.readOnly;
  var readOnly = _readOnly1 || _readOnly2;
  var parseRows = {};
  var tempItems = []; // 存放位置冲突或者未配置位置的扩展字段的FormItem

  Object.keys(rows).forEach(function (i) {
    if (!allConfigFields.includes(i)) {
      newFields.push({
        fieldCode: i
      });
    }
  });
  var baseCol = Math.floor(24 / maxCol);
  newFields.forEach(function (i) {
    var conditionHeaderDTOs = i.conditionHeaderDTOs,
        fieldType = i.fieldType,
        fieldCode = i.fieldCode,
        fieldName = i.fieldName,
        formRow = i.formRow,
        formCol = i.formCol,
        textMaxLength = i.textMaxLength,
        textMinLength = i.textMinLength,
        renderOptions = i.renderOptions,
        labelCol = i.labelCol,
        wrapperCol = i.wrapperCol,
        renderRule = i.renderRule,
        conValidDTO = i.conValidDTO,
        dateFormat = i.dateFormat,
        colSpan = i.colSpan;

    var _coverConfig = coverConfig({
      required: i.required,
      visible: i.visible,
      editable: i.editable
    }, conditionHeaderDTOs, {
      getValueFromCache: getValueFromCache,
      code: code
    }),
        required = _coverConfig.required,
        visible = _coverConfig.visible,
        editable = _coverConfig.editable;

    if (visible === 0) {
      // eslint-disable-next-line no-unused-expressions
      if (renderOptions === 'WIDGET' && form) {
        form.getFieldDecorator(fieldCode, {
          initialValue: undefined,
          rules: [{
            required: false
          }]
        });
      }

      return;
    }

    var selfRules = selfValidator(conValidDTO, {
      getValueFromCache: getValueFromCache,
      code: code
    });

    if (!rows[fieldCode]) {
      if (visible === -1) return; // 排除保留原有逻辑的显示控制

      var newRowProps = {
        className: 'writable-row' // individualProps.rowProps

      };
      var newColProps = {
        span: colSpan !== undefined ? baseCol * colSpan : baseCol // individualProps.colProps

      };
      var formItem;
      var formOptions = {
        fieldType: fieldType,
        required: required,
        textMaxLength: textMaxLength,
        textMinLength: textMinLength,
        fieldName: fieldName,
        selfRules: selfRules,
        dateFormat: dateFormat
      };
      var wrapProps = {
        label: fieldName,
        className: "cust-field-".concat(fieldCode),
        labelCol: {
          span: labelCol || unitLabelCol
        },
        wrapperCol: {
          span: wrapperCol || unitWrapperCol
        }
      };

      if (!_isNil(renderRule)) {
        formItem = getComputeComp(renderRule, {
          wrapProps: wrapProps,
          unitData: unitData
        });
      } else {
        formItem = getFormItemComponent(fieldType, renderOptions)({
          form: form,
          readOnly: readOnly,
          fieldCode: fieldCode,
          formOptions: formOptions,
          contentProps: _objectSpread(_objectSpread({}, i), {}, {
            style: {
              width: '100%'
            },
            getValueFromCache: getValueFromCache,
            editable: editable,
            unitLabelCol: unitLabelCol,
            unitWrapperCol: unitWrapperCol,
            dataSource: dataSource
          }),
          wrapProps: wrapProps
        });
      }

      adjustRowAndCol(parseRows, formItem, {
        row: formRow,
        col: formCol,
        tempItems: tempItems,
        rowProps: newRowProps,
        colProps: newColProps
      });
    } else {
      adapterStandardFormIndividual(_objectSpread(_objectSpread({}, i), {}, {
        editable: editable,
        selfRules: selfRules,
        required: required
      }), rows[fieldCode], parseRows, {
        baseCol: baseCol,
        form: form,
        unitLabelCol: unitLabelCol,
        unitWrapperCol: unitWrapperCol,
        dataSource: dataSource,
        tempItems: tempItems
      });
    }
  });
  var configRows = Object.keys(parseRows).sort(function (prev, next) {
    return Number(prev) - Number(next);
  });
  var tempRowStart = Number(configRows[configRows.length > 0 ? configRows.length - 1 : 0]) + 1;
  tempItems.forEach(function (item, index) {
    var row = Math.floor(index / maxCol) + tempRowStart;
    var col = index % maxCol;

    if (!parseRows[row]) {
      parseRows[row] = {
        rowProps: {},
        formItemList: []
      };
      configRows.push(row);
    }

    parseRows[row].rowProps = item.rowProps;
    parseRows[row].formItemList[col] = {
      colProps: item.colProps,
      formItem: item.formItem
    };
  });
  return /*#__PURE__*/React.createElement(Form, {
    className: className || 'writable-row-custom'
  }, configRows.map(function (key) {
    return /*#__PURE__*/React.createElement(Row, Object.assign({
      gutter: 48
    }, parseRows[key].rowProps), // eslint-disable-next-line func-names
    function (row) {
      var cols = [];
      var oldCols = row.formItemList;

      for (var i = 0; i < oldCols.length; i++) {
        if (!oldCols[i] && (row.rowProps.className || '').indexOf('half-row') === -1) {
          cols.push( /*#__PURE__*/React.createElement(Col, {
            span: Math.floor(24 / maxCol)
          }));
        } else if (oldCols[i]) {
          var _oldCols$i = oldCols[i],
              formItem = _oldCols$i.formItem,
              colProps = _oldCols$i.colProps;
          cols.push( /*#__PURE__*/React.createElement(Col, colProps, formItem));
        }
      }

      return cols;
    }(parseRows[key]));
  }));
}
export function generateTableColumns(columns) {
  var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

  var _ref = arguments.length > 2 ? arguments[2] : undefined,
      unitData = _ref.unitData,
      code = _ref.code,
      getValueFromCache = _ref.getValueFromCache,
      _readOnly1 = _ref.readOnly;

  var _config$fields2 = config.fields,
      fields = _config$fields2 === void 0 ? [] : _config$fields2,
      _readOnly2 = config.readOnly;
  var readOnly = _readOnly1 || _readOnly2;
  var noWidthCount = 0;
  var noneStandardSeq = columns.length;
  var scrollWidth = 0;
  var configOrder = []; // 记录租户个性化的位置信息，个性化顺序优先级高于原有配置

  var individualColumns = {}; // 个性化处理后的列对象，key值为调整后的顺序

  var columnsObj = {};
  var noConfigColumns = [];
  var allConfigFields = fields.map(function (i) {
    return i.fieldCode;
  });
  columns.forEach(function (i, index) {
    if (allConfigFields.includes(i.dataIndex)) {
      columnsObj[i.dataIndex] = index;
    } else {
      scrollWidth += i.width || 0;
      noConfigColumns.push(index);
    }
  }); // 配置拆分

  fields.forEach(function (i) {
    var defaultValue = i.defaultValue,
        _i$conditionHeaderDTO = i.conditionHeaderDTOs,
        conditionHeaderDTOs = _i$conditionHeaderDTO === void 0 ? [] : _i$conditionHeaderDTO,
        fieldCode = i.fieldCode,
        fieldType = i.fieldType,
        fixed = i.fixed,
        fieldName = i.fieldName,
        seq = i.seq,
        sorter = i.sorter,
        textMaxLength = i.textMaxLength,
        textMinLength = i.textMinLength,
        renderOptions = i.renderOptions,
        renderRule = i.renderRule,
        _i$conValidDTO = i.conValidDTO,
        conValidDTO = _i$conValidDTO === void 0 ? {} : _i$conValidDTO,
        dateFormat = i.dateFormat;

    var _coverConfig2 = coverConfig({
      visible: i.visible
    }, conditionHeaderDTOs.filter(function (k) {
      return k.conType === 'visible';
    }), {
      getValueFromCache: getValueFromCache,
      isGridVisible: true,
      currentUnitCode: code
    }),
        visible = _coverConfig2.visible;

    if (visible === 0) return;

    if (columnsObj[i.fieldCode] !== undefined) {
      var oldItem = columns[columnsObj[i.fieldCode]];
      var oldRender = oldItem.render;
      var width = i.width === undefined ? oldItem.width : i.width;
      var order = columnsObj[i.fieldCode];

      if (_isNumber(seq)) {
        configOrder.push(seq - 1);
        order = seq - 1;
      }

      if (_isNumber(width)) {
        oldItem.width = width;
        scrollWidth += width;
      } else noWidthCount++;

      if (fixed) {
        oldItem.fixed = fixedMap[fixed];
      }

      if (fieldName) {
        oldItem.title = fieldName;
      }

      if (sorter) {
        oldItem.sorter = true;
      }

      oldItem.render = function (val, record) {
        var meaning = record["".concat(fieldCode, "Meaning")];
        if (meaning === undefined) meaning = record[fieldCode];
        var _status = record._status;

        if (['update', 'create'].includes(_status) && oldRender) {
          var toolsObj = {
            isGrid: true,
            targetForm: record.$form,
            targetDataSource: record,
            getValueFromCache: getValueFromCache,
            currentUnitCode: code
          };

          var _coverConfig3 = coverConfig({
            required: i.required,
            editable: i.editable
          }, conditionHeaderDTOs.filter(function (k) {
            return k.conType !== 'visible';
          }), toolsObj),
              required = _coverConfig3.required,
              editable = _coverConfig3.editable;

          var selfRules = selfValidator(conValidDTO, toolsObj);
          var rules = customizeFormRules(_objectSpread(_objectSpread({}, i), {}, {
            required: required,
            selfRules: selfRules,
            fieldName: i.fieldName || oldItem.title
          }));
          var formItem = oldRender(val, record);
          formItem = _isNil(formItem) ? {} : formItem;
          traversalFormItems(formItem, _objectSpread(_objectSpread({}, _omit(i, ['fieldName'])), {}, {
            defaultValue: preAdapterInitValue(fieldType, defaultValue),
            rules: rules,
            editable: editable,
            form: record.$form,
            dataSource: record
          }));
          return formItem;
        }

        return oldRender ? oldRender(val, record) : getRender(fieldType, {
          precision: i.numberPrecision
        })(fieldType === 'LOV' || fieldType === 'SELECT' ? meaning : val);
      };

      if (individualColumns[order] === undefined) {
        individualColumns[order] = [];
      }

      individualColumns[order].push(oldItem);
    } else {
      if (visible === -1) return;
      noneStandardSeq++;
      var _order = noneStandardSeq;

      if (_isNumber(i.width)) {
        scrollWidth += i.width;
      } else noWidthCount++;

      if (_isNumber(seq)) {
        configOrder.push(seq - 1);
        _order = seq - 1;
      }

      var render = function render(val, record) {
        var _status = record._status,
            $form = record.$form;
        var meaning = record["".concat(fieldCode, "Meaning")];
        if (meaning === undefined) meaning = record[fieldCode];

        if (!_isNil(renderRule) && (renderOptions !== 'WIDGET' || readOnly)) {
          return getComputeComp(renderRule, {
            isGrid: true,
            dataSource: record,
            unitData: unitData,
            form: $form
          });
        }

        var selfRules = {};
        var wrapProps = {
          className: "cust-field-".concat(fieldCode)
        };
        var formOptions = {
          fieldType: fieldType,
          textMaxLength: textMaxLength,
          textMinLength: textMinLength,
          fieldName: fieldName,
          dateFormat: dateFormat
        };
        var isEdit = false;

        var contentProps = _objectSpread(_objectSpread({}, i), {}, {
          style: {
            width: '100%'
          },
          getValueFromCache: getValueFromCache,
          isGrid: true,
          dataSource: record
        });

        var toolsObj = {
          isGrid: true,
          targetForm: $form,
          targetDataSource: record,
          getValueFromCache: getValueFromCache,
          currentUnitCode: code
        };

        if (['update', 'create'].includes(_status)) {
          isEdit = true;

          var _coverConfig4 = coverConfig({
            required: i.required,
            editable: i.editable
          }, conditionHeaderDTOs.filter(function (k) {
            return k.conType !== 'visible';
          }), toolsObj),
              required = _coverConfig4.required,
              editable = _coverConfig4.editable;

          selfRules = selfValidator(conValidDTO, toolsObj);
          formOptions.required = required;
          formOptions.selfRules = selfRules;
          contentProps.editable = editable;
        }

        return getFormItemComponent(fieldType, renderOptions, code)({
          isEdit: isEdit,
          readOnly: readOnly,
          form: $form,
          defaultValue: defaultValue,
          formOptions: formOptions,
          contentProps: contentProps,
          fieldCode: fieldCode,
          wrapProps: wrapProps
        });
      };

      if (individualColumns[_order] === undefined) {
        individualColumns[_order] = [];
      }

      individualColumns[_order].push({
        width: i.width === undefined ? 200 : i.width,
        fixed: fixedMap[fixed],
        title: fieldName,
        sorter: !!sorter,
        dataIndex: fieldCode,
        render: render
      });
    }
  });
  noConfigColumns.forEach(function (i) {
    if (individualColumns[i] !== undefined) {
      individualColumns[i].push(columns[i]);
    } else {
      individualColumns[i] = [columns[i]];
    }
  });
  var left = [];
  var right = [];
  var normal = [];
  Object.keys(individualColumns).sort(function (pre, next) {
    return Number(pre || 0) - Number(next || 0);
  }).forEach(function (key) {
    var item = individualColumns[key]; // eslint-disable-next-line eqeqeq

    if (key == undefined) {
      item.forEach(function (i) {
        if (i.fixed === 'left') {
          left.unshift(i);
        } else if (i.fixed === 'right') {
          right.unshift(i);
        } else {
          normal.unshift(i);
        }
      });
    } else {
      item.forEach(function (i) {
        if (i.fixed === 'left') {
          left.push(i);
        } else if (i.fixed === 'right') {
          right.push(i);
        } else {
          normal.push(i);
        }
      });
    }
  });

  if (normal.length > 0 && (left.length > 0 || right.length > 0)) {
    scrollWidth -= normal[normal.length - 1].width || 0;
    noWidthCount++;
    normal[normal.length - 1].width = undefined;
  }

  return {
    noWidthCount: noWidthCount,
    scrollWidth: scrollWidth,
    columns: left.concat(normal).concat(right)
  };
}
export function generateFilterForm() {
  var formMap = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var fields = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  var options = arguments.length > 2 ? arguments[2] : undefined;
  var form = options.form,
      _options$unitLabelCol = options.unitLabelCol,
      unitLabelCol = _options$unitLabelCol === void 0 ? 10 : _options$unitLabelCol,
      _options$unitWrapperC = options.unitWrapperCol,
      unitWrapperCol = _options$unitWrapperC === void 0 ? 14 : _options$unitWrapperC,
      unitData = options.unitData,
      getValueFromCache = options.getValueFromCache;
  var individualField = []; // 个性化处理后的列对象，key值为调整后的顺序

  var allConfigFields = [];
  var newFields = [];
  fields.forEach(function (i) {
    allConfigFields.push(i.fieldCode);
    newFields.push(i);
  });
  Object.keys(formMap).forEach(function (i) {
    if (!allConfigFields.includes(i)) {
      newFields.push({
        fieldCode: i
      });
    }
  });
  newFields.sort(function (pre, next) {
    return (pre.seq || 0) - (next.seq || 0);
  }); // 配置拆分

  newFields.forEach(function (i) {
    var fieldCode = i.fieldCode,
        fieldType = i.fieldType,
        required = i.required,
        editable = i.editable,
        fieldName = i.fieldName,
        visible = i.visible,
        textMaxLength = i.textMaxLength,
        textMinLength = i.textMinLength,
        labelCol = i.labelCol,
        wrapperCol = i.wrapperCol,
        defaultValue = i.defaultValue,
        renderRule = i.renderRule,
        renderOptions = i.renderOptions,
        dateFormat = i.dateFormat;

    if (visible === 0) {
      // eslint-disable-next-line no-unused-expressions
      form && form.getFieldDecorator(fieldCode, {
        initialValue: undefined,
        rules: [{
          required: false
        }]
      });
      return;
    }

    if (formMap[fieldCode] !== undefined) {
      var rules = customizeFormRules(i);
      traversalFormItems(formMap[fieldCode], _objectSpread(_objectSpread({}, i), {}, {
        defaultValue: preAdapterInitValue(fieldType, defaultValue),
        rules: rules,
        editable: editable,
        form: form
      }));
      individualField.push(formMap[fieldCode]);
    } else {
      if (visible === -1) return;
      var formItem;

      if (!_isNil(renderRule)) {
        formItem = getComputeComp(renderRule, {
          isGrid: true,
          unitData: unitData
        });
      } else {
        formItem = getFormItemComponent(fieldType, renderOptions)({
          form: form,
          fieldCode: fieldCode,
          formOptions: {
            fieldType: fieldType,
            required: required,
            textMaxLength: textMaxLength,
            textMinLength: textMinLength,
            fieldName: fieldName,
            dateFormat: dateFormat
          },
          contentProps: _objectSpread(_objectSpread({}, i), {}, {
            style: {
              width: '100%'
            },
            getValueFromCache: getValueFromCache,
            editable: editable
          }),
          wrapProps: {
            label: fieldName,
            labelCol: {
              span: labelCol || unitLabelCol
            },
            wrapperCol: {
              span: wrapperCol || unitWrapperCol
            }
          }
        });
      }

      individualField.push(formItem);
    }
  });
  return individualField;
}